package com.example.springbootexp03demo.controllers;

import com.example.springbootexp03demo.models.StatData;
import com.example.springbootexp03demo.services.CrawlVirusData;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class StatController {

    // 用final修饰一个引用时，如果引用是类的成员变量，则必须当场赋值，否则编译会报错
    private final CrawlVirusData crawlVirusData;

    // ?将CrawlVirusData类实例化，
    public StatController(CrawlVirusData crawlVirusData) {
        this.crawlVirusData = crawlVirusData;
    }

    @GetMapping("/{country}")
    public String index(Model model, @PathVariable(value = "country") String country) {

        List<StatData> allStats;

        if (country == null || country.equals("all"))
            allStats = crawlVirusData.getAllStats();
        else
            allStats = crawlVirusData.getAllStats()
                    .parallelStream()
                    .filter(locationStats -> locationStats.getCountry().equals(country))
                    .collect(Collectors.toUnmodifiableList());   // toUnmodifiableList方法创建不可修改的集合,Collectors类收集不可修改的集合（Set，List，Map）

        /**
         * 往前台传数据，可以传对象，可以传List，通过el表达式 ${}可以获取到，
         * 类似于request.setAttribute("value",value)效果一样。
         * @param attributeName the name of the model attribute (never {@code null})
         * @param attributeValue the model attribute value (can be {@code null})
         */
        model.addAttribute("country", country);

        // 通过mapToInt将allStats中的latestTotalCases一一取出并组成一个流
        int totalReportedCases = allStats.parallelStream().mapToInt(StatData::getLatestTotalCases).sum();
        int totalNewCases = allStats.parallelStream().mapToInt(StatData::getDiffFromPrevDay).sum();

        model.addAttribute("stats", allStats);
        model.addAttribute("totalReportedCases", totalReportedCases);
        model.addAttribute("totalNewCases", totalNewCases);

        model.addAttribute("localDateTime", LocalDateTime.now());

        return "index";
    }
}

